package com.jzy.hzit.controller.admin;

import com.jzy.hzit.entity.LoginUser;
import com.jzy.hzit.entity.User;
import com.jzy.hzit.service.TokenService;
import com.jzy.hzit.service.UserService;
import com.jzy.hzit.utils.JwtUtil;
import com.jzy.hzit.utils.R;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/user")
@Api(tags = "用户登录、注册接口")
public class UserLoginController {

	@Autowired
	private UserServiceImpl userService; // 明确使用实现类，假设UserService有一个实现类UserServiceImpl

	@Autowired
	private TokenServiceImpl tokenService; // 明确使用实现类，假设TokenService有一个实现类TokenServiceImpl

	// 1. 用户登录
	@PostMapping("/login")
	@ApiOperation("用户登录")
	public R login(
			@ApiParam(value = "登录用户信息", required = true)
			@RequestBody User loginRequest) {
		// 1.1 根据用户名和密码查询用户
		LoginUser loginUser = userService.authenticate(loginRequest.getUsername(), loginRequest.getPassword());
		if (loginUser == null) {
			return R.error().message("用户名或密码错误");
		}
		Map<String, Object> tokenMap = tokenService.generateToken(loginUser);
		return R.success().data(tokenMap);
	}

	@GetMapping("/info")
	public R getUserInfo(@RequestParam("token") String token) {
		try {
			Claims claims = JwtUtil.extractClaims(token); // 假设JwtUtil有一个extractClaims方法用于解析token
			String username = claims.getSubject(); // 通常JWT的subject字段存储用户名

			Map<String, String> userInfo = new HashMap<>();
			userInfo.put("name", username);
			userInfo.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
			return R.success().data(userInfo);
		} catch (Exception e) {
			return R.error().message("无效的token");
		}
	}

	@PostMapping("/signIn")
	public R userSignUp(@RequestBody User signUpRequest) {
		boolean isRegistered = userService.registerUser(signUpRequest);
		if (isRegistered) {
			return R.success().code(200).message("注册成功");
		} else {
			return R.error().message("注册失败");
		}
	}
}
